package com.addzero.kmp.util

import com.addzero.kmp.processor.entity.JdbcColumnMetadata
import com.addzero.kmp.util.TypeMapper.toLowCamelCase


/**
 * 代码生成工具类
 */
object CodeGeneratorUtil {
    /**
     * 生成属性注释
     */
    fun generatePropertyDoc(column: JdbcColumnMetadata): String {
        return """
            |    /**
            |     * ${if (column.remarks.isNotEmpty()) column.remarks else column.columnName}
            |     * 
            |     * 数据库列名: ${column.columnName}
            |     * 数据类型: ${column.columnType}
            |     * ${if (column.isPrimaryKey) "主键: 是" else ""}
            |     * 可空: ${if (column.nullable) "是" else "否"}
            |     * ${if (column.defaultValue != null) "默认值: ${column.defaultValue}" else ""}
            |     */
        """.trimMargin()
    }

    /**
     * 生成类注释
     */
    fun generateClassComment(
        className: String,
        interfaceName: String? = null,
        tableRemarks: String,
        unsupportedTypes: List<String>
    ): String {
        return buildString {
            append("/**\n")
            append(" * $className${if (interfaceName != null) " 实现类\n * 实现 $interfaceName 接口" else ""}\n")
            if (tableRemarks.isNotEmpty()) {
                append(" * $tableRemarks\n")
            }
            if (unsupportedTypes.isNotEmpty()) {
                append(" * \n")
                append(" * 不支持的字段类型:\n")
                unsupportedTypes.forEach { type ->
                    append(" * $type\n")
                }
            }
            append(" */")
        }
    }

    /**
     * 生成属性定义
     */
    fun generateProperty(
        column: JdbcColumnMetadata,
        kotlinType: String,
        isOverride: Boolean = false
    ): String {
        val camelCaseName = column.columnName.toLowCamelCase()
        val doc = generatePropertyDoc(column)
        val override = if (isOverride) "override " else ""
        return "$doc\n    $override val $camelCaseName: $kotlinType${if (column.nullable) "?" else ""}"
    }
}
